import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/home/Home'
import Center from '@/components/home/center'
import Login from '@/components/login/login'
import User from '@/components/sys/user'
import Role from '@/components/sys/role'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/login',
      name: '登录页',
      component: Login
    },
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: '/index',
      // 首页 登录后才能访问
      meta: {
        requireAuth: true
      },
      children: [
        {
          path: 'index',
          name: '首页',
          component: Center
        },
        {
          path: 'user',
          name: '用户管理',
          component: User
        },
        {
          path: 'role',
          name: '角色管理',
          component: Role
        }
      ]
    }
  ]
})

//  判断是否需要登录权限 以及是否登录
router.beforeEach((to, from, next) => {
  if (to.matched.some(res => res.meta.requireAuth)) {// 判断是否需要登录权限
    // 判断是否登录
    if (localStorage.getItem('username')) {
      next()
    } else {
      // 没登录则跳转到登录界面
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router